package com.lollipop.synthential.ip;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @Author: J.K
 * @Date: 2022-06-09 10:52
 * @Description:
 */
public class JacksonUtils {
    /**
     * 获取 jack object mapper 实例
     *
     * @return
     */
    public static ObjectMapper getObjectMapper() {
        return ObjectMapperHolder.objectMapper;
    }

    /**
     * 将json字符串反序列化为指定类型的对象
     *
     * @param json
     * @param clazz
     * @return
     */
    public static Object jsonToObject(String json, Class clazz) {
        if (json != null) {
            try {
                return getObjectMapper().readValue(json, clazz);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    /**
     * 将对象序列化为json字符串
     *
     * @param object
     * @return
     */
    public static String writeValueAsString(Object object) {
        ObjectMapper objectMapper1 = getObjectMapper();
        try {
            return objectMapper1.writeValueAsString(object);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 单例
     */

    private static class ObjectMapperHolder {
        private static ObjectMapper objectMapper;

        static {
            objectMapper = new ObjectMapper();
        }
    }
}
